package com.ztom.daily.n2022.m4;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * N 叉树的层次遍历
 * <p>
 * https://leetcode-cn.com/problems/n-ary-tree-level-order-traversal/
 *
 * @author ZhangTao
 */
public class Day08LevelOrder {

    class Node {
        public int val;
        public List<Node> children;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<Node> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int curLevelSize = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < curLevelSize; i++) {
                Node node = queue.poll();
                if (node == null) continue;
                list.add(node.val);
                for (Node child : node.children) {
                    queue.offer(child);
                }
            }
            res.add(list);
        }

        return res;
    }
}
